<script setup lang="ts">
// /api/admin/profits/total-stats
import { useDark, useECharts } from "@pureadmin/utils";
import { ref, watch, nextTick, PropType } from "vue";
import { generatePalette } from "@/plugins/echarts";

// TS 类型定义
interface StatsByServiceItem {
  serviceType: string;
  cost: number;
  profit: number;
  sales: number;
  task_count: number;
}
interface StatsByCountryItem {
  country: string;
  cost: number;
  profit: number;
  sales: number;
  task_count: number;
}
interface StatsByTimeItem {
  period: string;
  cost: number;
  profit: number;
  sales: number;
  task_count: number;
}

// 组件 prop，传入整个系统收益统计数据对象
const props = defineProps({
  data: {
    type: Array as PropType<
      StatsByServiceItem[] | StatsByCountryItem[] | StatsByTimeItem[]
    >,
    default: () => []
  }
});

// 图表初始化
const chartRef = ref<HTMLDivElement>();
const themeName = "lowSaturationFancy";
const { isDark } = useDark();
const { setOptions } = useECharts(chartRef, { theme: themeName });

// 渲染服务类型收益饼图
watch(
  () => props.data,
  async (
    list: StatsByServiceItem[] | StatsByCountryItem[] | StatsByTimeItem[]
  ) => {
    await nextTick();
    const seriesData = list.map(item => ({
      value: item.profit,
      name: item.serviceType || item.country || item.period
    }));
    const colors = generatePalette(seriesData.length);

    setOptions({
      color: colors,
      tooltip: { trigger: "item", formatter: "{b}: {c} ({d}%)" },
      legend: {
        type: "scroll",
        orient: "vertical",
        left: "left",
        textStyle: { color: isDark.value ? "#fff" : "#666" }
      },
      series: [
        {
          name: "服务类型收益",
          type: "pie",
          radius: ["30%", "70%"],
          center: ["50%", "50%"],
          roseType: "radius", // 启用南丁格尔玫瑰图（半径模式）
          itemStyle: {
            borderRadius: 4
          },
          data: seriesData,
          label: {
            show: true,
            fontSize: 12,
            formatter: "{b}: {c}"
          },
          labelLine: { length: 12, length2: 4 },
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowColor: "rgba(0,0,0,0.5)" }
          }
        }
      ]
    });
  },
  { immediate: true }
);
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 365px" />
</template>
